
package kaizone.haining.chaobohui.widget;

import java.util.ArrayList;
import java.util.List;

import kaizone.haining.chaobohui.R;
import kaizone.haining.chaobohui.CBHApplication;
import kaizone.haining.chaobohui.activity.CBHActivity;
import kaizone.haining.chaobohui.args.AppArgs;
import kaizone.haining.chaobohui.fragment.ImageDetailFragment;
import kaizone.haining.chaobohui.json.Banner;
import kaizone.haining.chaobohui.json.BannerDO;
import kaizone.haining.chaobohui.json.Banner.PicModel;
import kaizone.haining.chaobohui.net.DataControl;
import kaizone.haining.chaobohui.util.ImageFetcher;
import kaizone.haining.chaobohui.util.Utils;
import kaizone.haining.chaobohui.util.ImageCache.ImageCacheParams;
import android.app.Activity;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.ImageView.ScaleType;

public class SlideFrameLayout extends FrameLayout implements DataControl.IDataUpdateListener {

    // private int[] mDrawableResId = {
    // R.drawable.banner1, R.drawable.banner2, R.drawable.banner3,
    // R.drawable.banner4
    // };
    //
    // private String[] mTexts = {
    // "郭敬明雷军有望同台对话潮城", // 0
    // "方大同杨宗纬刘忻唱响潮音乐节", // 1
    // "微诗歌赢大奖 诵出给志摩的爱", // 2
    // "聚合新媒体的力量 助力城市发展", // 3
    // };
    //
    // private String[] mUrls = {
    // "http://zj.sina.com.cn/hd/econ_trendsetter/index.html", // 0
    // "http://static.dp-app.com/download/yinyuejie.html", // 1
    // "http://http://zj.sina.com.cn/xzm2013/index.html", // 2
    // "http://www.chinaleather.com/", // 3
    // };

    private ViewPager mPager;

    // private List<ImageView> mImageViews;
    private List<Object> mData = new ArrayList<Object>();

    private TextView mTextView;

    private int mPosition;

    private int mWidth;

    private int mHeight;

    private FragmentManager mFragmentManager;

    private ImagePagerAdapter mAdapter;

    private DataControl mDataControl;

    public SlideFrameLayout(Context context) {
        super(context);
        init();
    }

    public SlideFrameLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    private void init() {
        initParams();
        initFragmentManager();
        initControl();
        // mImageViews = new ArrayList<ImageView>();
        //
        // final int len = mDrawableResId.length;
        // for (int i = 0; i < len; i++) {
        // ImageView imageView = new ImageView(getContext());
        // Bitmap bm =
        // ImageResizer.decodeSampledBitmapFromResource(getResources(),
        // mDrawableResId[i], mWidth, mHeight);
        // imageView.setImageBitmap(bm);
        // imageView.setScaleType(ScaleType.FIT_XY);
        // imageView.setClickable(true);
        // imageView.setOnClickListener(this);
        // mImageViews.add(imageView);
        // }
    }

    private void initParams() {
        if (getContext() instanceof Activity) {
            Activity activity = (Activity) getContext();
            DisplayMetrics dm = new DisplayMetrics();
            activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
            final int dispalyWidth = dm.widthPixels;
            mWidth = dispalyWidth;
            float f = 34f / 67;
            mHeight = (int) (f * mWidth);
        }
    }

    private void initFragmentManager() {
        if (getContext() instanceof Activity) {
            mFragmentManager = ((CBHActivity) getContext()).getSupportFragmentManager();
        }
    }

    public void initControl() {
        mDataControl = new DataControl(getContext());
        mDataControl.addChangeListener(this);
        if (AppArgs.sBannerDO == null) {
            mDataControl.exec(BannerDO.URL);
        } else {
            initBannerDo();
        }
    }

    private void initBannerDo() {
        BannerDO bannerDO = AppArgs.sBannerDO;
        Banner banner = bannerDO.getBanner(Banner.INDEX);
        if (banner == null) {
            mDataControl.exec(BannerDO.URL);
            return;
        }
        List<PicModel> items = banner.getPicModels();
        if (items == null || items.isEmpty()) {
            mDataControl.exec(BannerDO.URL);
            return;
        }
        mData.removeAll(mData);
        mData.addAll(items);
    }

    private void updateBanner(int args) {
        if (mTextView == null)
            return;
        if (mData == null && mData.isEmpty())
            return;
        if (args >= mData.size())
            return;
        PicModel picModel = (PicModel) mData.get(args);
        mTextView.setText(picModel.name);
    }

    private void click(int arg0) {
        if (mData == null && mData.isEmpty())
            return;
        if (mPosition >= mData.size())
            return;
        PicModel picModel = (PicModel) mData.get(arg0);
        if (picModel == null)
            return;
        final String urlString = picModel.clickUrl;
        Utils.openBrowser(getContext(), urlString);
    }

    @Override
    protected void onFinishInflate() {
        mTextView = (TextView) findViewById(R.id.tv01);

        mPager = (ViewPager) findViewById(R.id.pager);
        mAdapter = new ImagePagerAdapter(mFragmentManager);
        mPager.setAdapter(mAdapter);

        mPager.setOnPageChangeListener(new OnPageChangeListener() {

            @Override
            public void onPageSelected(int position) {
                mPosition = position;
                updateBanner(position);
            }

            @Override
            public void onPageScrolled(int postion, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        updateBanner(mPosition);
    }

    @Override
    public Object backParse(String datastring, String requeststring) {
        if (TextUtils.isEmpty(datastring))
            return null;
        if (TextUtils.isEmpty(requeststring))
            return null;
        if (requeststring.equals(BannerDO.URL)) {
            BannerDO bannerDO = BannerDO.parseJson(datastring);
            AppArgs.sBannerDO = bannerDO;
            return bannerDO;
        }
        return null;
    }

    @Override
    public void foreUpdate(Object result, String requeststring) {
        if (result == null)
            return;
        if (requeststring.equals(BannerDO.URL)) {
            BannerDO bannerDO = (BannerDO) result;
            Banner banner = bannerDO.getBanner(Banner.INDEX);
            if (banner == null)
                return;
            List<PicModel> items = banner.getPicModels();
            if (items == null || items.isEmpty())
                return;
            mData.removeAll(mData);
            mData.addAll(items);
            mAdapter.notifyDataSetChanged();
            updateBanner(0);
        }
    }

    @Override
    public void exception(Exception e) {
        // TODO Auto-generated method stub

    }

    public String getCurrentUrl() {

        if (mData == null && mData.isEmpty())
            return null;
        if (mPosition >= mData.size())
            return null;
        PicModel picModel = (PicModel) mData.get(mPosition);
        return picModel.clickUrl;
    }

    //
    // private class MyPagerAdapter extends PagerAdapter {
    // @Override
    // public boolean isViewFromObject(View arg0, Object arg1) {
    // return arg0 == arg1;
    // }
    //
    // @Override
    // public int getCount() {
    // return mImageViews.size();
    // }
    //
    // @Override
    // public void destroyItem(ViewGroup container, int position, Object object)
    // {
    // container.removeView(mImageViews.get(position));
    // }
    //
    // @Override
    // public Object instantiateItem(ViewGroup container, int position) {
    // container.addView(mImageViews.get(position));
    // return mImageViews.get(position);
    // }
    // }
    //
    private class ImagePagerAdapter extends FragmentStatePagerAdapter {

        public ImagePagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public int getCount() {
            return mData != null ? mData.size() : 0;
        }

        @Override
        public Fragment getItem(int position) {

            PicModel item = (PicModel) mData.get(position);
            if (item == null)
                return null;
            String url = item.picUrl;

            ImageDetailFragment instance = ImageDetailFragment.newInstance(url, 1);
            instance.setListener(new ImageDetailFragment.OnClickListener() {
                @Override
                public void onClick(View v) {
                    click(mPosition);
                }
            });
            return instance;
        }
    }

    public static SlideFrameLayout sInstance;

    public static SlideFrameLayout newInstance(Context context) {
        if (sInstance == null) {
            final SlideFrameLayout f = (SlideFrameLayout) View.inflate(context,
                    R.layout.home_image, null);
            sInstance = f;
        }
        return sInstance;
    }

}
